package com.my.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.my.reggie.common.R;
import com.my.reggie.pojo.Category;
import com.my.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;
    /**
     * 分页查询
     * @param page  当前页码
     * @param pageSize 每页显示条数
     * @return R<Page></page>
     */
    @GetMapping("/page")
    public R<Page<Category>> page(int page, int pageSize){
        //构造分页构造器
        Page<Category> pageInfo = new Page<>(page,pageSize);
        //构造条件过滤器
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.orderByAsc(Category::getSort);
        //执行查询
        categoryService.page(pageInfo,lqw);
        return R.success(pageInfo);
    }

    /**
     * 新增菜品分类
     * @return R<String>
     */
    @PostMapping
    public R<String> save(@RequestBody Category category){
        boolean is_succeed = categoryService.save(category);
        if(is_succeed){
            return R.success("添加成功！");
        } else{
            return R.error("添加失败！");
        }
    }

    /**
     * 修改信息
     * @param category 传入参数
     * @return R<String>
     */
    @PutMapping
    public R<String> update(@RequestBody Category category){
        boolean is_succeed = categoryService.updateById(category);
        if(is_succeed){
            return R.success("修改成功！");
        } else{
            return R.error("修改失败!");
        }
    }

    /**
     * 删除分类
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(Long ids){
        categoryService.delete(ids);
        return R.success("分类信息删除成功！");
    }

    /**
     * 获取新增操作时的分类列表
     * @param category
     * @return
     */
    @GetMapping("/list")
    public R<List<Category>> getList(Category category){
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.eq(category.getType() != null,Category::getType,category.getType());
        lqw.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> categoryList = categoryService.list(lqw);
        return R.success(categoryList);
    }

}
